<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Companies;
use App\Province;
use	App\City;
use App\Area;
use App\User;
use Image;
use Redirect;
use Excel;

class CompanyController extends Controller
{
	public $province  = null;
	
	/**
	 * 设置分页大小
	 */
	public $pageSize = null;
	
	
	public function __construct()
	{
		$this->province	 = (new Province)->all();
		$this->pageSize	 = CS('admin_page_size')!=''?CS('admin_page_size'):20;
	}
	


	/**
	 * 获取企业列表
	 */
	public function index(Request $req)
	{
		//权限验证
		if(!in_array('com_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		
		$title = trans('admin.company_list');
		$com_id		= isset($req->com_id)?trim($req->com_id):'';
		$com_name	= isset($req->com_name)?htmlspecialchars((trim($req->com_name))):'';
		$status		= isset($req->status)?trim($req->status):'';
		$type		= isset($req->type)?trim($req->type):'';		
		$where = [];
		
		
		if($com_id !== '')
		{
			$where   =  array_merge($where, ['com_id' => $com_id]);
		}
	
		if($status !== '')
		{
			$where   =  array_merge($where, ['status' => $status]);
		}
		
		if($type !== '')
		{
			$where   =  array_merge($where, ['type' => $type]);
		}
		

		if($com_name !== '')
		{
			$data = Companies::orderBy('com_id','desc')
				->where($where)
				->where('com_name','like','%'.$com_name.'%')
            	->paginate($this -> pageSize);	
		}
		else
		{
			$data = Companies::orderBy('com_id','desc')
				->where($where)
	            ->paginate($this -> pageSize);				
		}
	
		return view('admin.company.company_list',['title'=>$title,
			'data'		=>	$data,
			'com_id' 	=>	$com_id, 
			'com_name' 	=> 	$com_name,
			'type'		=> 	$type,
			'status' 	=> 	$status,
		]);
	}

	
	
	/**
	 *	修改企业 
	 */
	public function update(Request $req,$id)
	{
		//权限验证
		if(!in_array('com_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		if(Companies::where('companies.com_id',$id)->count() < 1)
		{
			return redirect('admin/company');
		}
		$com	= Companies::where('companies.com_id',$id)
			->leftJoin('users', 'companies.user_id',  '=', 'users.id')
			->select('companies.*','users.name')
			->first();
		
		if($req->isMethod('get'))
		{
			$title 	= trans('admin.company_update');				
			$cities	= City::where('province_id',$com->province_id)->get();
			$areas	= Area::where('city_id',$com->city_id)->get();
			return view('admin.company.company_update',['title'=>$title,
				'province'  =>  $this->province,
				'com'		=> 	$com,
				'cities'	=>	$cities,
				'areas'		=>	$areas,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'com_name'	=> 'required|max:100',
	            'type'  	=> 'required|in:0,1',
	            'status'    => 'required|in:0,1',
	            'linkman'	=> 'required|max:20',
	            'telephone'	=> 'required|max:100',
	            'province_id'	=> 'required',
	            'city_id'		=> 'required',
	            'area_id'		=> 'required',
	            'address'		=> 'required|max:100',
	            'desc'			=> 'max:255',
	        ];
			
	        $message = [
	            'com_name.required'  => '企业名称是必须的',
				'com_name.max' 		 => '企业名称长度不能大于100',
	            'address.required'  => '详细地址是必须的',
				'address.max' 	 	=> '详细地址长度不能大于100',
				'desc.max' 	 		=> '详情长度不能大于255',
	            'linkman.required'  => '联系人是必须的',
				'linkman.max' 	 	=> '联系人长度不能大于20',
				'telephone.required'  	=> '联系电话是必须的',
				'telephone.max' 	 	=> '联系电话长度不能大于100',
				'province_id.required'  	=> '省/直辖市是必须的',
				'city_id.required'  		=> '市/直辖市是必须的',
				'area_id.required'  		=> '区/县是必须的',	
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			Companies::where('com_id',$id)
			->update(['com_name' => trim($input['com_name']),
				'status' => trim($input['status']),
				'type' 	 => trim($input['type']),
				'linkman'	=> trim($input['linkman']),
				'telephone' => trim($input['telephone']),
				'province_id' 	 	=> trim($input['province_id']),
				'city_id' 	 	=> trim($input['city_id']),
				'area_id' 	 	=> trim($input['area_id']),
				'address' 	 	=> trim($input['address']),			
				'desc' 	 		=> trim($input['desc']),			
			]);
			
			//营业执照图片处理
			if(isset($input['business_license']))
			{
				if($com -> business_license != '')
				{
					unlink(public_path($com -> business_license ));
				}
				
				$path = 'uploads/companies/'.date('Y/m/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['business_license'])->resize(400, 600);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Companies::where('com_id',$id)
				->update(['business_license' => $_oriPath]);				
			}

			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/company')
			]);
		}
	}
	

	/**
	 *	企业批量操作 
	 */
	public function companyHandle(Request $req)
	{
		//批量通过审核
		if($req->act == 'pass')
		{
			$in = array_flatten($req->items);
			Companies::whereIn('com_id',$in)
            ->update(['status' => 0]);
			return ['error'=>0,'message'=>'success'];
		}
		
		//批量取消审核
		if($req->act == 'unpass')
		{
			$in = array_flatten($req->items);
			Companies::whereIn('com_id',$in)
            ->update(['status' => 1]);
			return ['error'=>0,'message'=>'success'];
		}
		
	}
	
	
	
	
	
	/**
	 * 企业批量上传
	 */
	public function batchUpload(Request $req)
	{		
		//权限验证
		if(!in_array('com_import',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req->isMethod('get'))
		{
			$title = trans('admin.company_batch_upload');
			return view('admin.company.batch',[
				'title' 	=> 	$title,
				'province'  =>  $this->province,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'excel'   => 'required',
	        ];
			
	        $message = [
	            'excel.required' 	=> '请上传表格',
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
			
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			//处理上传excel文件并返回地址
			$file = excelUpload('brands',$req);

			$res = Excel::load($file, function($reader){})->toArray();
	
			foreach($res as $k => $v)
			{
				Companies::insert([
					'com_name' 		=> 	$v[0],
					'type'			=>	$v[1],
					'status'		=>	$v[2],
					'linkman'		=>	$v[3],
					'telephone'		=>	$v[4],
					'address'		=>	$v[5],
					'desc'			=>	$v[6],
					'add_time'		=>  time(),
					'province_id' 	=> 	$req->province_id,
  					'city_id'		=>  $req->city_id,
  					'area_id' 		=> 	$req->area_id,
				]);
			}
  			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.import_succ'),
				'url' => url('admin/company'),
			]);		
			
		}		
	}





















}
